<?php
class Gateway_model extends CI_Model {

	private $USER_TABLE = 'users';

	/**
	 * Validates an account login by verifying the account/password combination
	 *
	 * @param $input - Array with the entered account/password.
	 * @return The account name if the login is validated, nothing otherwise
	 */
	function validate($input){
		//Check if provided password is correct
		$row = $this->confirmPassword($input['account'], $input['password']);

		//If so, return account name.
		if(isset($row)){
			return $row['account'];
		}
	}

	/**
	 * Check if provided password for user is correct, if so, return row.
	 *
	 * @param $account - Account key
	 * @param $password - input password
	 * @return Row if password correct
	 */
	function confirmPassword($account, $password) {
		$this->db->where('account', $account);
		$query = $this->db->get($this->USER_TABLE);

		if($query->num_rows == 1){
			$res = $query->row_array();
				
			if($this->encryptPassword($password,$res['salt']) == $res['password']){
				return $res;
			}
		}
	}

	function check_access($account) {
		if(empty($account)) return NULL;

		$this->load->model('profile_model');
		return $this->profile_model->get_field($account, 'order');
	}

	/**
	 * Verifies if the user had elevated permissiosn (admin or leader)
	 * returns True/False
	 */
	function is_admin(){
		$account = $this->session->userdata('account');
		
		if (isset($account)){
			$order = $this->check_access($account);
			return ($order == 'admin' || $order == 'leader');
		} else {
			return false;
		}
	}

	/**
	 * Encrypt a cleartext password using the MD5 hash
	 *
	 * @param $cleartext - Clear text to be encrypted
	 * @param $salt - Salt used to encrypt password
	 * @return Encrypted clear text
	 */
	function encryptPassword($cleartext, $salt){
		$encrypted = md5($cleartext.$salt);
		return $encrypted;
	}

	/**
	 * Creates a new user profile in the database using information provided from the registration form
	 *
	 * @param $insert_data - Data passed from the form in the Register subview
	 */
	function create_account($insert_data){
		$salt = random_string('alnum', 32);
		$insert_data['salt'] = $salt;
		$insert_data['score'] = 1000;
		$insert_data['password'] = $this->encryptPassword($insert_data['password'], $salt);
		$insert = $this->db->insert($this->USER_TABLE, $insert_data);
		return $insert;
	}

}